import numpy as np
import cv2 as cv

# 初始化绘图状态
state = {
    'drawing': False,  # 是否正在绘图
    'mode': False,  # 绘图模式：False-圆形，True-矩形
    'start_point': (-1, -1),  # 起始点坐标
    'color': (0, 255, 0)  # 默认颜色
}


def draw_shape(event, x, y, flags, param):
    """
    鼠标回调函数
    :param event: 鼠标事件类型
    :param x, y: 当前鼠标位置
    :param flags: 事件标志
    :param param: 额外参数
    """
    global img, temp_img

    # 左键按下：开始绘图
    if event == cv.EVENT_LBUTTONDOWN:
        state['drawing'] = True
        state['start_point'] = (x, y)
        temp_img = img.copy()  # 创建临时图像用于实时预览

    # 鼠标移动：实时绘制
    elif event == cv.EVENT_MOUSEMOVE:
        if state['drawing']:
            # 复制临时图像以避免闪烁
            display_img = temp_img.copy()
            if state['mode']:  # 矩形模式
                cv.rectangle(display_img, state['start_point'], (x, y), state['color'], 2)
            else:  # 圆形模式
                radius = int(np.sqrt((x - state['start_point'][0]) ** 2 + (y - state['start_point'][1]) ** 2))
                cv.circle(display_img, state['start_point'], radius, state['color'], 2)
            cv.imshow('Drawing Board', display_img)

    # 左键释放：完成绘图
    elif event == cv.EVENT_LBUTTONUP:
        state['drawing'] = False
        if state['mode']:  # 绘制最终矩形
            cv.rectangle(img, state['start_point'], (x, y), state['color'], 2)
        else:  # 绘制最终圆形
            radius = int(np.sqrt((x - state['start_point'][0]) ** 2 + (y - state['start_point'][1]) ** 2))
            cv.circle(img, state['start_point'], radius, state['color'], 2)
        cv.imshow('Drawing Board', img)


def main():
    """主程序"""
    global img, temp_img

    # 创建黑色画布
    img = np.zeros((512, 512, 3), dtype=np.uint8)
    temp_img = img.copy()  # 初始化临时图像
    cv.namedWindow('Drawing Board')

    # 设置鼠标回调
    cv.setMouseCallback('Drawing Board', draw_shape)

    while True:
        # 显示当前图像
        cv.imshow('Drawing Board', img)

        # 键盘交互
        key = cv.waitKey(1) & 0xFF

        # 切换模式：矩形/圆形
        if key == ord('m'):
            state['mode'] = not state['mode']
            print(f"切换到 {'矩形' if state['mode'] else '圆形'} 模式")

        # 切换颜色
        elif key == ord('c'):
            state['color'] = tuple(np.random.randint(0, 256, 3).tolist())
            print(f"颜色更改为：{state['color']}")

        # 清空画布
        elif key == ord('r'):
            img.fill(0)
            temp_img = img.copy()
            print("画布已重置")

        # 退出程序
        elif key == 27:
            break

    cv.destroyAllWindows()


if __name__ == '__main__':
    main()